Page({
  data: { list: [] },

  onLoad() {
    this.pullList();          // 1. 先拉历史
    this.connectWS();         // 2. 再连 WebSocket 实时接收
  },

  // 拉取历史消息
  pullList() {
    wx.request({
      url: 'http://127.0.0.1:10877/wx_msg/list', // 替换为后端公网地址
      success: res => {
        console.log("666"+res.data.data);
        if (res.data.code === 200) {
          this.setData({ list:  res.data.data});
        }
      }
    });
  },

  // WebSocket 接收推送
  connectWS() {
    const ws = wx.connectSocket({ url: 'ws://your-domain.com:8081' });
    ws.onMessage(msg => {
      const { type, data } = JSON.parse(msg.data);
      if (type === 'add') {
        this.setData({ list: [data, ...this.data.list] }); // 新消息置顶
      }
    });
    ws.onError(e => console.log('WS error', e));
  },

  toDetailPage(event) {
    const { id } = event.currentTarget.dataset;   // 取 i
    console.log("id:"+id);
    wx.navigateTo({
      url: '/pages/message/detail/detail?id=${id}',
    })
  }
});